package cn.itcast.mq.listener;

import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.LocalTime;

@Component
public class SpringRabbitListener {

    //消费者1         从simple.queue队列中获取消息
    @RabbitListener(queues = "simple.queue")
    public void listenerSimpleQueueMessage1(String msg)throws InterruptedException{
        System.out.println("消费者1接收到消息: ["+msg+"]"+ LocalTime.now());
        Thread.sleep(20);
    }

    //消费者2         从simple.queue队列中获取消息
    @RabbitListener(queues = "simple.queue")
    public void listenerSimpleQueueMessage2(String msg)throws InterruptedException{
        System.out.println("消费者2接收到消息: ["+msg+"]"+LocalTime.now());
        Thread.sleep(200);
    }

    //Fanout模型的交换机
    @RabbitListener(queues = "fanout.queue1")
    public void listenFanoutQueue1(String msg){
        System.out.println("消费者1接收 到Fanout消息:{"+msg+"}");
    }
    //Fanout模型的交换机
    @RabbitListener(queues = "fanout.queue2")
    public void listenFanoutQueue2(String msg){
        System.out.println("消费者2接收 到Fanout消息:{"+msg+"}");
    }


    //Direct模型的交换机
    /**
     * 基于注解声明队列 交换机
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(
            // 使用注解定义 队列名称
            value = @Queue(name = "direct.queue1"),
            //使用注解 定义 交换机名称 交换机类型
            exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
            //此交换机依据key进行判断 只有队列的key与消息的key完全一致 才会接收到消息
            key = {"red","blue"}
    ))
    public void listenDirectQueue1(String msg){
        System.out.println("消费者接收到direct.queue1的消息:{"+msg+"}");
    }
    //Direct模型的交换机
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue2"),
            exchange = @Exchange(name = "itcast.direct",type = ExchangeTypes.DIRECT),
            key = {"red","yellow"}
    ))
    public void listenDirectQueue2(String msg){
        System.out.println("消费者接收到direct.queue2的消息:{"+msg+"}");
    }


    //Topic模型的交换机 和Direct不同的是在队列绑定Routing Key的时候可以使用通配符
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topic.queue1"),
            exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC),
            key = "china.#"
    ))
    public void listenTopicQueue1(String msg){
        System.out.println("消费者接收到topic.queue1的消息:{"+msg+"}");
    }

    //Topic模型交换机
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topic.queue2"),
            exchange =@Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC),
            key = "#.news"
    ))

    public void listenTopicQueue2(String msg){
        System.out.println("消费者接收到topic.queue1的消息:{"+msg+"}");
    }

}
